﻿/*
 * Copyright 2014 Francois Karman
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using Quartz.Ext;
using System;
using System.ComponentModel;
using System.IO;
using System.Net;

namespace Quartz.WebManager.BasicTasks
{
    /// <summary>
    /// Calls a predefined web page.
    /// </summary>
    [Property("pageUrl", PropertyTypes.Url, DisplayName = "Url of the page")]
    [DisplayName("Call a web page")]
    [Description("this job calls a specific url that could start with http:, https:, ftp: or file:")]
    public class CallWebPageJob : BaseJob
    {
        /// <summary>
        /// Calls a predefined web page and raised an exception for 4xx or 5xx errors.
        /// </summary>
        /// <param name="context">The execution context.</param>
        protected override void ProtectedExecute(IJobExecutionContext context)
        {
            Uri pageUrl = context.MergedJobDataMap.GetUri("pageUrl");
            using (WebClient client = new WebClient())
            {
                client.UseDefaultCredentials = true;
                Stream stream = null;
                try
                {
                    stream = client.OpenRead(pageUrl);
                }
                catch (WebException exception)
                {
                    string format = "The page {0} can't be loaded - {1}";
                    string message = string.Format(format, pageUrl, exception.Message);
                    throw new JobExecutionException(message, null, false);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }
            }
        }
    }
}
